<template>
  <div style="padding: 20px">
    <el-page-header content="缓存问卷列表" @back="goBack" />

    <div style="margin: 20px 0; display: flex; gap: 10px">
      <!--      <el-button type="primary" @click="goToFill">➕ 填写问卷</el-button>-->
      <el-button type="success" :disabled="!multipleSelection.length" @click="batchUpload">⬆️ 批量上传</el-button>
    </div>

    <el-table v-loading="loading" :data="surveys" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="updatedAt" label="保存时间">
        <template #default="scope">
          {{ new Date(scope.row.updatedAt).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="edit(scope.row)">编辑</el-button>
          <el-button size="small" type="primary" @click="uploadPic(scope.row)">图片</el-button>
          <el-button size="small" type="primary" @click="uploadOne(scope.row)">上传</el-button>
        </template>
      </el-table-column>
    </el-table>
    <UploadPic ref="uploadPicRef" @ok="uploadPicCallback" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { useRouter } from "vue-router"
import { deleteSurvey, getSurveys } from "@/db/localDb"
import { post } from "@/common/api"
import UploadPic from "./components/UploadPic.vue"

const surveys = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const loading = ref(false)
const router = useRouter()
const uploadPicRef = ref()

const load = async () => {
  loading.value = true
  surveys.value = await getSurveys()
  surveys.value.sort((a, b) => b.updatedAt - a.updatedAt)

  console.log("列表", surveys.value)
  loading.value = false
}

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const goBack = () => router.push("/main")

// const goToFill = () => {
//   router.push({ path: "/fill", query: { id: null } })
// }

const edit = (survey: any) => {
  router.push({ path: "/fill", query: { id: survey.id } })
}

const uploadPic = (record: any) => {
  uploadPicRef.value.show(record)
}

const uploadPicCallback = () => {
  load()
}

const uploadOne = async (survey: any) => {
  let updata = JSON.parse(JSON.stringify(survey))
  updata.quesData = JSON.stringify(updata.quesData)
  try {
    loading.value = true

    const res = await post("/survey/upload", updata)
    if (res.code === 200) {
      await deleteSurvey(survey.id)
      ElMessage.success("上传成功")
      await load()
    } else {
      ElMessage.error(res.message)
    }
  } catch (e) {
    ElMessage.error("上传失败")
  } finally {
    loading.value = false
  }
}

const batchUpload = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请先选择要上传的问卷")
    return
  }

  try {
    await ElMessageBox.confirm(`确认上传选中的 ${multipleSelection.value.length} 条问卷？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })

    const successList: string[] = []
    const failList: string[] = []

    for (const survey of multipleSelection.value) {
      let updata = JSON.parse(JSON.stringify(survey))
      updata.quesData = JSON.stringify(updata.quesData)
      try {
        const res = await post("/survey/upload", updata)

        if (res.code === 200) {
          await deleteSurvey(survey.id)
          successList.push(survey.id)
        } else {
          console.error("上传失败", res)
          failList.push(survey.id)
        }
      } catch (err) {
        console.error("上传异常", err)
        failList.push(survey.id)
      }
    }

    if (successList.length) {
      ElMessage.success(`成功上传 ${successList.length} 条问卷`)
    }
    if (failList.length) {
      ElMessage.error(`有 ${failList.length} 条问卷上传失败`)
    }

    load() // 重新加载本地问卷列表
  } catch (e) {
    ElMessage.info("已取消上传")
  }
}

onMounted(load)
</script>
